import { _decorator, Component, Node, Button, instantiate } from 'cc'
import { ResMgr } from './ResMgr'

export class UICtrl extends Component {

  protected view = {}

  loadAllObj(root, path) {
    for (let i = 0; i < root.children.length; i++) {
      this.view[path + root.children[i].name] = root.children[i]
      this.loadAllObj(root.children[i], path + root.children[i].name + '/')
    }
  }

  onLoad() {
    this.view = {}
    this.loadAllObj(this.node, '')
  }

  public addButtonListen(viewName, caller, func) {
    let viewNode = this.view[viewName]
    if (!viewNode) return
    let button = viewNode.getComponent(Button)
    if (!button) return
    viewNode.on('click', func, caller)
  }
}

export class UIMgr extends Component {
  public static Instance: UIMgr = null
  private Canvas: Node = null
  private uiMap = {}

  onLoad() {
    if (UIMgr.Instance === null) {
      console.log('[UIMgr] Instance')
      UIMgr.Instance = this
    } else {
      console.log('[UIMgr] Instance Destroy')
      this.destroy()
      return
    }
    this.Canvas = this.node
  }

  public showUI(uiName, parent?: Node): Node {
    if (!parent) parent = this.Canvas
    let prefab = ResMgr.Instance.getAsset('GUI', 'UIPrefabs/' + uiName)
    let item = null
    if (prefab) {
      item = instantiate(prefab)
      parent.addChild(item)
      console.log(`[UIMgr] Add Component ${uiName}_Ctrl`)
      item.addComponent(uiName + '_Ctrl')
    }
    this.uiMap[uiName] = item
    return item
  }

  public removeUI(uiName) {
    if (this.uiMap[uiName]) {
      console.log(`[UIMgr] Remove UI ${uiName}`)
      this.uiMap[uiName].removeFromParent()
      this.uiMap[uiName] = null
    }
  }

  public clearAll() {
    for (let uiName in this.uiMap) {
      if (this.uiMap[uiName]) {
        console.log(`[UIMgr] Clear UI ${uiName}`)
        this.uiMap[uiName].removeFromParent()
        this.uiMap[uiName] = null
      }
    }
  }

  public hideUI(uiName) {
    let comp = this.Canvas.getChildByName(uiName)
    if (!comp) return
    comp.active = false
  }
}
